<template>
  <div class="home">
    <div class="header">
      <h1>H5测试应用</h1>
      <p>运营商外呼接口测试</p>
    </div>
    
    <div class="content">
      <div class="auth-section">
        <h2>用户鉴权</h2>
        <button 
          class="auth-btn" 
          :class="{ 'authenticated': isAuthenticated }"
          @click="handleAuth"
        >
          {{ isAuthenticated ? '已鉴权' : '点击鉴权' }}
        </button>
        <p class="status-text" v-if="authMessage">{{ authMessage }}</p>
        
        <!-- 鉴权结果显示区域 -->
        <div class="auth-result" v-if="authResult">
          <h3>鉴权详细信息</h3>
          <pre class="result-content">{{ authResult }}</pre>
        </div>
      </div>

      <div class="call-section">
        <h2>外呼功能</h2>
        <div class="phone-input">
          <input 
            type="tel" 
            v-model="phoneNumber" 
            placeholder="请输入手机号码"
            class="phone-input-field"
          />
        </div>
        <button 
          class="call-btn" 
          :disabled="!isAuthenticated || !phoneNumber"
          @click="handleCall"
        >
          拨打电话
        </button>
        <p class="status-text" v-if="callMessage">{{ callMessage }}</p>
        
        <!-- 外呼结果显示区域 -->
        <div class="call-result" v-if="callResult">
          <h3>外呼详细信息</h3>
          <pre class="result-content">{{ callResult }}</pre>
        </div>
      </div>

      <div class="agent-section">
        <h2>查询坐席信息</h2>
        <div class="agent-info">
          <p>查询坐席分机号: {{ Exten }}</p>
        </div>
        <button 
          class="agent-btn" 
          :disabled="!isAuthenticated"
          @click="handleQueryAgent"
        >
          查询坐席
        </button>
        <p class="status-text" v-if="agentMessage">{{ agentMessage }}</p>
        
        <!-- 坐席查询结果显示区域 -->
        <div class="agent-result" v-if="agentResult">
          <h3>坐席详细信息</h3>
          <pre class="result-content">{{ agentResult }}</pre>
        </div>
      </div>
    </div>

    <!-- 手机号输入弹窗 -->
    <div class="modal" v-if="showPhoneModal" @click="closePhoneModal">
      <div class="modal-content" @click.stop>
        <h3>输入本机号码</h3>
        <p>请输入您的手机号码进行身份验证</p>
        <div class="phone-input-container">
          <input 
            type="tel" 
            v-model="userPhoneNumber" 
            placeholder="请输入11位手机号码"
            class="phone-input-modal"
            maxlength="11"
            @input="validatePhoneInput"
          />
          <div class="phone-error" v-if="phoneError">{{ phoneError }}</div>
        </div>
        <div class="modal-buttons">
          <button class="modal-btn cancel" @click="closePhoneModal">取消</button>
          <button class="modal-btn confirm" @click="confirmPhoneNumber" :disabled="!isPhoneValid">确认</button>
        </div>
      </div>
    </div>

    <!-- 提示弹窗 -->
    <div class="modal" v-if="showModal" @click="closeModal">
      <div class="modal-content" @click.stop>
        <h3>{{ modalTitle }}</h3>
        <p>{{ modalMessage }}</p>
        <button class="modal-btn" @click="closeModal">确定</button>
      </div>
    </div>
  </div>
</template>

<script>
import { ref } from 'vue'
import CryptoJS from 'crypto-js'

export default {
  name: 'Home',
  setup() {
    const isAuthenticated = ref(false)
    const phoneNumber = ref('')
    const authMessage = ref('')
    const callMessage = ref('')
    const showModal = ref(false)
    const modalTitle = ref('')
    const modalMessage = ref('')
    const authResult = ref('')
    const callResult = ref('')
    
    // 坐席查询相关状态
    const agentMessage = ref('')
    const agentResult = ref('')
    
    // 手机号相关状态
    const showPhoneModal = ref(false)
    const userPhoneNumber = ref('')
    const phoneError = ref('')
    const isPhoneValid = ref(false)
    const cachedPhoneNumber = ref('')

    // 鉴权配置
    const ACCOUNT_ID = 'N00000063989'
    const API_SECRET = 'f65b4210-765c-11f0-af7b-b78475a2f3d5'
    const API_URL = 'https://apis.7moor.com/'
    const FromExten = '8000'
    const Exten = '8000'

    // 生成时间戳 (yyyyMMddHHmmss)
    const generateTimestamp = () => {
      const now = new Date()
      const year = now.getFullYear()
      const month = String(now.getMonth() + 1).padStart(2, '0')
      const day = String(now.getDate()).padStart(2, '0')
      const hours = String(now.getHours()).padStart(2, '0')
      const minutes = String(now.getMinutes()).padStart(2, '0')
      const seconds = String(now.getSeconds()).padStart(2, '0')
      return `${year}${month}${day}${hours}${minutes}${seconds}`
    }

    // 生成签名
    const generateSignature = (accountId, apiSecret, timestamp) => {
      const signString = accountId + apiSecret + timestamp
      return CryptoJS.MD5(signString).toString().toUpperCase()
    }

    // 手机号验证函数
    const validatePhoneNumber = (phone) => {
      const phoneRegex = /^1[3-9]\d{9}$/
      return phoneRegex.test(phone)
    }

    // 手机号输入验证
    const validatePhoneInput = () => {
      const phone = userPhoneNumber.value.trim()
      if (!phone) {
        phoneError.value = ''
        isPhoneValid.value = false
        return
      }
      
      if (phone.length < 11) {
        phoneError.value = '手机号码长度不足'
        isPhoneValid.value = false
      } else if (!validatePhoneNumber(phone)) {
        phoneError.value = '请输入正确的手机号码格式'
        isPhoneValid.value = false
      } else {
        phoneError.value = ''
        isPhoneValid.value = true
      }
    }

    // 从缓存加载手机号
    const loadCachedPhoneNumber = () => {
      try {
        const cached = localStorage.getItem('userPhoneNumber')
        if (cached) {
          cachedPhoneNumber.value = cached
          return ''
        }
      } catch (error) {
        console.error('读取缓存手机号失败:', error)
      }
      return null
    }

    // 保存手机号到缓存
    const savePhoneNumberToCache = (phone) => {
      try {
        localStorage.setItem('userPhoneNumber', phone)
        cachedPhoneNumber.value = phone
        console.log('手机号已保存到缓存:', phone)
      } catch (error) {
        console.error('保存手机号到缓存失败:', error)
      }
    }

    // 关闭手机号弹窗
    const closePhoneModal = () => {
      showPhoneModal.value = false
      userPhoneNumber.value = ''
      phoneError.value = ''
      isPhoneValid.value = false
    }

    // 确认手机号
    const confirmPhoneNumber = () => {
      if (isPhoneValid.value) {
        savePhoneNumberToCache(userPhoneNumber.value)
        closePhoneModal()
        // 继续执行鉴权
        performAuthentication()
      }
    }

    // Base64编码
    const generateAuthorization = (accountId, timestamp) => {
      const authString = `${accountId}:${timestamp}`
      return btoa(authString)
    }

    // 鉴权函数
    const authenticate = async () => {
      try {
        const timestamp = generateTimestamp()
        const sig = generateSignature(ACCOUNT_ID, API_SECRET, timestamp)
        const authorization = generateAuthorization(ACCOUNT_ID, timestamp)
        
        const url = `${API_URL}v20160818/customer/getTemplate/${ACCOUNT_ID}?sig=${sig}`
        
        const headers = {
          'Content-Type': 'application/json;charset=utf-8',
          'Authorization': authorization
        }

        console.log('鉴权参数:', {
          timestamp,
          sig,
          authorization,
          url,
          headers
        })

        const response = await fetch(url, {
          method: 'POST',
          headers: headers,
          body: JSON.stringify({})
        })

        const result = await response.json()
        
        // 根据API文档处理返回值
        const isSuccess = result.code === 200
        
        return {
          success: isSuccess,
          data: result,
          code: result.code,
          message: result.message,
          authData: result.data || null,
          status: response.status,
          timestamp,
          sig,
          authorization
        }
      } catch (error) {
        console.error('鉴权错误:', error)
        return {
          success: false,
          error: error.message,
          timestamp: generateTimestamp()
        }
      }
    }

    // 修改坐席手机号函数
    const updateUserMobile = async (mobile, timestamp) => {
      try {
        const sig = generateSignature(ACCOUNT_ID, API_SECRET, timestamp)
        const authorization = generateAuthorization(ACCOUNT_ID, timestamp)
        
        const url = `${API_URL}v20160818/user/updateUser/${ACCOUNT_ID}?sig=${sig}`
        
        const requestBody = {
          exten: Exten,
          mobile: mobile
        }
        
        const headers = {
          'Content-Type': 'application/json;charset=utf-8',
          'Authorization': authorization
        }

        console.log('修改坐席手机号参数:', {
          url,
          headers,
          body: requestBody,
          timestamp,
          sig
        })

        const response = await fetch(url, {
          method: 'POST',
          headers: headers,
          body: JSON.stringify(requestBody)
        })

        const result = await response.json()
        
        // 根据API文档处理返回值
        const isSuccess = result.code === 200
        
        return {
          success: isSuccess,
          data: result,
          code: result.code,
          message: result.message,
          status: response.status,
          requestBody,
          timestamp,
          sig,
          authorization
        }
      } catch (error) {
        console.error('修改坐席手机号错误:', error)
        return {
          success: false,
          error: error.message,
          timestamp
        }
      }
    }

    // 查询坐席信息函数
    const queryAgentInfo = async (exten) => {
      try {
        const timestamp = generateTimestamp()
        const sig = generateSignature(ACCOUNT_ID, API_SECRET, timestamp)
        const authorization = generateAuthorization(ACCOUNT_ID, timestamp)
        
        const url = `${API_URL}v20160818/account/getCCAgentsByAcc/${ACCOUNT_ID}?sig=${sig}`
        
        const requestBody = {
          Exten: exten
        }
        
        const headers = {
          'Content-Type': 'application/json;charset=utf-8',
          'Authorization': authorization
        }

        console.log('查询坐席信息参数:', {
          url,
          headers,
          body: requestBody,
          timestamp,
          sig
        })

        const response = await fetch(url, {
          method: 'POST',
          headers: headers,
          body: JSON.stringify(requestBody)
        })

        const result = await response.json()
        
        // 根据API文档处理返回值
        const isSuccess = result.code === 200
        
        return {
          success: isSuccess,
          data: result,
          code: result.code,
          message: result.message,
          agentData: result.data || null,
          status: response.status,
          requestBody,
          timestamp,
          sig,
          authorization
        }
      } catch (error) {
        console.error('查询坐席信息错误:', error)
        return {
          success: false,
          error: error.message,
          timestamp: generateTimestamp()
        }
      }
    }

    // 执行鉴权的核心逻辑
    const performAuthentication = async () => {
      authMessage.value = '正在进行鉴权...'
      
      try {
        const result = await authenticate()
        
        if (result.success) {
           isAuthenticated.value = true
           authMessage.value = '鉴权成功！'
           
           // 鉴权成功后，自动调用修改坐席手机号
           const updateResult = await updateUserMobile(cachedPhoneNumber.value, result.timestamp)
           
           // 合并显示鉴权和修改坐席手机号的结果
            const combinedResult = {
              auth: {
                status: '成功',
                code: result.code,
                message: result.message,
                timestamp: result.timestamp,
                sig: result.sig.substring(0, 16) + '...',
                authorization: result.authorization.substring(0, 20) + '...',
                responseStatus: result.status,
                authData: result.authData
              },
              updateMobile: {
                status: updateResult.success ? '成功' : '失败',
                mobile: cachedPhoneNumber.value,
                exten: Exten,
                code: updateResult.code,
                message: updateResult.message,
                responseStatus: updateResult.status,
                errorMsg: updateResult.error || null
              },
              phoneNumber: cachedPhoneNumber.value
            }
           authResult.value = JSON.stringify(combinedResult, null, 2)
           
           showModal.value = true
           modalTitle.value = '鉴权成功'
           
           let modalMsg = `API调用成功！\n\n✅ 鉴权状态: 已通过 (${result.code})\n📱 本机号码: ${cachedPhoneNumber.value}\n🕐 时间戳: ${result.timestamp}\n🔐 签名: ${result.sig.substring(0, 16)}...\n📝 状态码: ${result.status}\n💬 消息: ${result.message}`
           
           if (updateResult.success) {
              modalMsg += `\n\n📞 坐席手机号更新: 成功\n📱 绑定号码: ${cachedPhoneNumber.value}\n📋 坐席号: 8000\n✅ 响应码: ${updateResult.code}`
            } else {
              let errorDetail = ''
              switch(updateResult.code) {
                case 210:
                  errorDetail = '坐席不存在'
                  break
                case 400:
                  errorDetail = '请求体参数错误'
                  break
                case 403:
                  errorDetail = '鉴权参数错误'
                  break
                case 500:
                  errorDetail = '服务器错误'
                  break
                default:
                  errorDetail = updateResult.message || updateResult.error || '未知错误'
              }
              modalMsg += `\n\n❌ 坐席手机号更新: 失败\n📝 响应码: ${updateResult.code}\n⚠️ 错误信息: ${errorDetail}`
            }
           
           modalMsg += `\n\n可以使用外呼功能了！`
           modalMessage.value = modalMsg
        } else {
           authMessage.value = '鉴权失败'
           
           // 根据错误码提供详细的错误信息
           let errorDetail = ''
           switch(result.code) {
             case 400:
               errorDetail = '请求体参数错误，请检查传递的参数是否合法'
               break
             case 403:
               errorDetail = '鉴权失败，请检查账户ID、API密钥或时间戳是否正确'
               break
             default:
               errorDetail = result.message || result.error || '未知错误'
           }
           
           // 简化显示的失败信息
           const simplifiedError = {
             status: '失败',
             code: result.code,
             message: result.message,
             timestamp: result.timestamp,
             responseStatus: result.status,
             errorDetail,
             errorMsg: result.error || null
           }
           authResult.value = JSON.stringify(simplifiedError, null, 2)
           
           showModal.value = true
           modalTitle.value = '鉴权失败'
           modalMessage.value = `❌ API调用失败\n\n🕐 时间戳: ${result.timestamp}\n📝 响应码: ${result.code}\n💬 消息: ${result.message}\n⚠️ 错误详情: ${errorDetail}\n\n请检查网络连接或联系管理员`
         }
      } catch (error) {
        authMessage.value = '鉴权异常'
        showModal.value = true
        modalTitle.value = '鉴权异常'
        modalMessage.value = `发生异常: ${error.message}`
      }
    }

    const handleAuth = async () => {
      if (!isAuthenticated.value) {
        // 检查是否有缓存的手机号
        const cachedPhone = loadCachedPhoneNumber()
        
        if (cachedPhone && validatePhoneNumber(cachedPhone)) {
          // 有有效的缓存手机号，直接进行鉴权
          await performAuthentication()
        } else {
          // 没有缓存或缓存无效，弹出手机号输入框
          showPhoneModal.value = true
        }
      } else {
        // 重新鉴权
        isAuthenticated.value = false
        authMessage.value = ''
        authResult.value = ''
        callMessage.value = ''
        callResult.value = ''
      }
    }

    // 生成唯一ActionID
    const generateActionID = () => {
      return 'ACTION_' + Date.now() + '_' + Math.random().toString(36).substr(2, 9)
    }

    // 外呼函数
    const dialout = async (targetPhone) => {
      try {
        const timestamp = generateTimestamp()
        const sig = generateSignature(ACCOUNT_ID, API_SECRET, timestamp)
        const authorization = generateAuthorization(ACCOUNT_ID, timestamp)
        
        const url = `${API_URL}v20180426/call/dialout/${ACCOUNT_ID}?sig=${sig}`
        
        const requestBody = {
          FromExten: FromExten,
          Exten: targetPhone,
          ExtenType: 'Local',
          ActionID: generateActionID(),
          DialoutStrVar: '',
          OutShow: ''
        }
        
        const headers = {
          'Content-Type': 'application/json;charset=utf-8',
          'Authorization': authorization
        }

        console.log('外呼参数:', {
          url,
          headers,
          body: requestBody
        })

        const response = await fetch(url, {
          method: 'POST',
          headers: headers,
          body: JSON.stringify(requestBody)
        })

        const result = await response.json()
        
        // 根据API文档处理外呼返回值
        const isSuccess = result.Succeed === true || result.Succeed === 'true'
        
        return {
          success: isSuccess,
          data: result,
          response: result.Response,
          actionID: result.ActionID,
          succeed: result.Succeed,
          message: result.Message,
          status: response.status,
          requestBody,
          timestamp
        }
      } catch (error) {
        console.error('外呼错误:', error)
        return {
          success: false,
          error: error.message,
          timestamp: generateTimestamp()
        }
      }
    }

    const handleCall = async () => {
      if (!isAuthenticated.value) {
        showModal.value = true
        modalTitle.value = '鉴权失败'
        modalMessage.value = '请先进行用户鉴权'
        return
      }

      if (!phoneNumber.value) {
        showModal.value = true
        modalTitle.value = '参数错误'
        modalMessage.value = '请输入有效的手机号码'
        return
      }

      callMessage.value = '正在发起外呼...'
      
      try {
        const result = await dialout(phoneNumber.value)
        
        if (result.success) {
           callMessage.value = `外呼成功 - ${phoneNumber.value}`
           
           // 显示详细的外呼信息
           const detailedCallResult = {
             status: '成功',
             targetPhone: phoneNumber.value,
             response: result.response,
             actionID: result.actionID,
             succeed: result.succeed,
             message: result.message,
             timestamp: result.timestamp,
             responseStatus: result.status,
             fromExten: result.requestBody.FromExten
           }
           callResult.value = JSON.stringify(detailedCallResult, null, 2)
           
           showModal.value = true
           modalTitle.value = '外呼成功'
           modalMessage.value = `📞 外呼请求已发送\n\n🎯 目标号码: ${phoneNumber.value}\n📋 ActionID: ${result.actionID}\n✅ 处理结果: ${result.succeed}\n🕐 时间戳: ${result.timestamp}\n📝 状态码: ${result.status}\n\n外呼正在进行中...`
         } else {
           callMessage.value = '外呼失败'
           
           // 根据Message字段提供详细的错误信息
            let errorDetail = ''
            const message = result.message || ''
            
            if (message.includes('400') && message.toLowerCase().includes('error')) {
              errorDetail = '请求有误，请检查传递的参数是否合法'
            } else if (message.includes('401') && (message.toLowerCase().includes('pbx') || message.toLowerCase().includes('notfound'))) {
              errorDetail = '账户配置问题'
            } else if (message.includes('402') && message.toLowerCase().includes('agent')) {
              errorDetail = '坐席未绑定手机号，请检查对应手机号是否存在'
            } else if (message.includes('403') && message.toLowerCase().includes('allowed')) {
              errorDetail = '用户账户或验证码无效或过期，请技术支持修改账户属性，允许这个账户使用外呼接口'
            } else if (message.includes('403') && message.toLowerCase().includes('forbbiden')) {
              errorDetail = '鉴权失败'
            } else if (message.includes('404') && message.toLowerCase().includes('agent')) {
              errorDetail = '坐席未找到，请检查FromExten字段中的坐席分机号是否传递正确'
            } else if (message.includes('407') && message.toLowerCase().includes('take')) {
              errorDetail = '坐席无法接听电话（坐席没有登录），可通过传ExtenType解决该问题'
            } else if (message.includes('408') && message.toLowerCase().includes('busy')) {
              errorDetail = '坐席忙碌，无法接听（坐席已经有一通电话在进行中）'
            } else if (message.includes('409') && message.toLowerCase().includes('available')) {
              errorDetail = '调用者指定的接听方式不可用。可能原因：软电话未登陆，网关未绑定或未注册，未绑定手机号'
            } else if (message.includes('500') && message.toLowerCase().includes('server')) {
              errorDetail = '服务器错误'
            } else if (message.toLowerCase().includes('sip') && message.toLowerCase().includes('login')) {
              errorDetail = '对应接听方式不可用，可能原因：软电话未登陆，网关未绑定或未注册，未绑定手机号'
            } else {
              errorDetail = result.message || result.error || '未知错误'
            }
           
           const detailedCallError = {
             status: '失败',
             targetPhone: phoneNumber.value,
             response: result.response,
             actionID: result.actionID,
             succeed: result.succeed,
             message: result.message,
             timestamp: result.timestamp,
             errorCode: result.status || 'N/A',
             errorDetail: errorDetail
           }
           callResult.value = JSON.stringify(detailedCallError, null, 2)
           
           showModal.value = true
           modalTitle.value = '外呼失败'
           modalMessage.value = `❌ 外呼请求失败\n\n🎯 目标号码: ${phoneNumber.value}\n📋 ActionID: ${result.actionID || 'N/A'}\n❌ 处理结果: ${result.succeed}\n🕐 时间戳: ${result.timestamp}\n📝 状态码: ${result.status || 'N/A'}\n⚠️ 错误信息: ${errorDetail}\n\n请根据错误信息进行相应处理`
         }
      } catch (error) {
        callMessage.value = '外呼异常'
        showModal.value = true
        modalTitle.value = '外呼异常'
        modalMessage.value = `发生异常: ${error.message}`
      }
    }

    // 处理查询坐席信息
    const handleQueryAgent = async () => {
      if (!isAuthenticated.value) {
        agentMessage.value = '请先进行鉴权'
        return
      }
      
      agentMessage.value = '正在查询坐席信息...'
      
      try {
        const result = await queryAgentInfo(Exten)
        
        if (result.success) {
          agentMessage.value = '查询成功！'
          
          // 显示详细的坐席信息
          const detailedAgentResult = {
            status: '成功',
            queryExten: Exten,
            code: result.code,
            message: result.message,
            agentData: result.agentData,
            timestamp: result.timestamp,
            responseStatus: result.status,
            requestBody: result.requestBody
          }
          agentResult.value = JSON.stringify(detailedAgentResult, null, 2)
          
          showModal.value = true
          modalTitle.value = '查询成功'
          modalMessage.value = `✅ 坐席信息查询成功\n\n📋 查询分机号: ${Exten}\n📝 响应码: ${result.code}\n💬 消息: ${result.message}\n🕐 时间戳: ${result.timestamp}\n📊 状态码: ${result.status}`
        } else {
          agentMessage.value = '查询失败'
          
          // 根据错误码提供详细的错误信息
          let errorDetail = ''
          switch(result.code) {
            case 400:
              errorDetail = '请求体参数错误，请检查传递的参数是否合法'
              break
            case 403:
              errorDetail = '鉴权失败，请检查账户ID、API密钥或时间戳是否正确'
              break
            case 404:
              errorDetail = '坐席未找到，请检查分机号是否正确'
              break
            default:
              errorDetail = result.message || result.error || '未知错误'
          }
          
          const detailedAgentError = {
            status: '失败',
            queryExten: Exten,
            code: result.code,
            message: result.message,
            errorDetail,
            timestamp: result.timestamp,
            responseStatus: result.status,
            errorMsg: result.error || null
          }
          agentResult.value = JSON.stringify(detailedAgentError, null, 2)
          
          showModal.value = true
          modalTitle.value = '查询失败'
          modalMessage.value = `❌ 坐席信息查询失败\n\n📋 查询分机号: ${Exten}\n📝 响应码: ${result.code}\n💬 消息: ${result.message}\n⚠️ 错误详情: ${errorDetail}\n\n请检查分机号或联系管理员`
        }
      } catch (error) {
        agentMessage.value = '查询异常'
        showModal.value = true
        modalTitle.value = '查询异常'
        modalMessage.value = `发生异常: ${error.message}`
      }
    }

    const closeModal = () => {
      showModal.value = false
    }

    return {
      isAuthenticated,
      phoneNumber,
      authMessage,
      callMessage,
      showModal,
      modalTitle,
      modalMessage,
      authResult,
      callResult,
      showPhoneModal,
      userPhoneNumber,
      phoneError,
      isPhoneValid,
      agentMessage,
      agentResult,
      Exten,
      handleAuth,
      handleCall,
      handleQueryAgent,
      closeModal,
      closePhoneModal,
      confirmPhoneNumber,
      validatePhoneInput
    }
  }
}
</script>

<style scoped>
.home {
  min-height: 100vh;
  padding: 20px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.header {
  text-align: center;
  color: white;
  margin-bottom: 40px;
}

.header h1 {
  font-size: 2.5em;
  margin-bottom: 10px;
  text-shadow: 2px 2px 4px rgba(0,0,0,0.3);
}

.header p {
  font-size: 1.2em;
  opacity: 0.9;
}

.content {
  max-width: 400px;
  margin: 0 auto;
}

.auth-section, .call-section, .agent-section {
  background: white;
  border-radius: 15px;
  padding: 30px;
  margin-bottom: 20px;
  box-shadow: 0 8px 32px rgba(0,0,0,0.1);
}

.auth-section h2, .call-section h2, .agent-section h2 {
  color: #333;
  margin-bottom: 20px;
  font-size: 1.5em;
}

.auth-btn, .call-btn, .agent-btn {
  width: 100%;
  padding: 15px;
  border: none;
  border-radius: 10px;
  font-size: 1.1em;
  font-weight: bold;
  cursor: pointer;
  transition: all 0.3s ease;
  margin-bottom: 15px;
}

.auth-btn {
  background: linear-gradient(45deg, #4CAF50, #45a049);
  color: white;
}

.auth-btn.authenticated {
  background: linear-gradient(45deg, #2196F3, #1976D2);
}

.auth-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 15px rgba(0,0,0,0.2);
}

.call-btn {
  background: linear-gradient(45deg, #FF6B6B, #FF5252);
  color: white;
}

.call-btn:disabled {
  background: #ccc;
  cursor: not-allowed;
  transform: none;
}

.call-btn:not(:disabled):hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 15px rgba(0,0,0,0.2);
}

.agent-btn {
  background: linear-gradient(45deg, #9C27B0, #7B1FA2);
  color: white;
}

.agent-btn:disabled {
  background: #ccc;
  cursor: not-allowed;
  transform: none;
}

.agent-btn:not(:disabled):hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 15px rgba(0,0,0,0.2);
}

.phone-input, .agent-info {
  margin-bottom: 20px;
  padding: 15px;
  background: #f8f9fa;
  border-radius: 8px;
  border-left: 4px solid #9C27B0;
}

.agent-info p {
  margin: 0;
  color: #333;
  font-weight: 500;
}

.phone-input-field {
  width: 100%;
  padding: 15px;
  border: 2px solid #ddd;
  border-radius: 10px;
  font-size: 1.1em;
  box-sizing: border-box;
  transition: border-color 0.3s ease;
}

.phone-input-field:focus {
  outline: none;
  border-color: #667eea;
}

/* 手机号输入弹窗样式 */
.phone-input-container {
  margin: 20px 0;
}

.phone-input-modal {
  width: 100%;
  padding: 12px 15px;
  border: 2px solid #ddd;
  border-radius: 8px;
  font-size: 16px;
  box-sizing: border-box;
  transition: border-color 0.3s ease;
}

.phone-input-modal:focus {
  outline: none;
  border-color: #667eea;
}

.phone-error {
  color: #ff4444;
  font-size: 14px;
  margin-top: 8px;
  text-align: left;
}

.modal-buttons {
  display: flex;
  gap: 15px;
  margin-top: 25px;
}

.modal-btn.cancel {
  background: #f5f5f5;
  color: #666;
  border: 1px solid #ddd;
}

.modal-btn.cancel:hover {
  background: #e9e9e9;
}

.modal-btn.confirm {
  background: linear-gradient(45deg, #4CAF50, #45a049);
  color: white;
}

.modal-btn.confirm:disabled {
  background: #ccc;
  cursor: not-allowed;
}

.modal-btn.confirm:not(:disabled):hover {
  background: linear-gradient(45deg, #45a049, #4CAF50);
}

.status-text {
  color: #666;
  font-size: 0.9em;
  margin-top: 10px;
  text-align: center;
}

.modal {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0,0,0,0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.modal-content {
  background: white;
  padding: 30px;
  border-radius: 15px;
  max-width: 350px;
  width: 90%;
  text-align: center;
  box-shadow: 0 10px 40px rgba(0,0,0,0.3);
}

.modal-content h3 {
  color: #333;
  margin-bottom: 15px;
  font-size: 1.3em;
}

.modal-content p {
  color: #666;
  line-height: 1.5;
  margin-bottom: 20px;
  white-space: pre-line;
}

.modal-btn {
  background: linear-gradient(45deg, #667eea, #764ba2);
  color: white;
  border: none;
  padding: 12px 30px;
  border-radius: 8px;
  font-size: 1em;
  cursor: pointer;
  transition: all 0.3s ease;
}

.modal-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 15px rgba(0,0,0,0.2);
}

.auth-result, .call-result, .agent-result {
  margin-top: 20px;
  padding: 15px;
  background: #f8f9fa;
  border-radius: 8px;
}

.auth-result {
  border-left: 4px solid #667eea;
}

.call-result {
  border-left: 4px solid #FF6B6B;
}

.agent-result {
  border-left: 4px solid #9C27B0;
}

.auth-result h3, .call-result h3, .agent-result h3 {
  margin: 0 0 10px 0;
  color: #333;
  font-size: 1.1em;
}

.result-content {
  background: #fff;
  padding: 12px;
  border-radius: 6px;
  border: 1px solid #e0e0e0;
  font-size: 0.85em;
  line-height: 1.4;
  color: #555;
  overflow-x: auto;
  white-space: pre-wrap;
  word-wrap: break-word;
  max-height: 300px;
  overflow-y: auto;
}

@media (max-width: 480px) {
  .home {
    padding: 10px;
  }
  
  .header h1 {
    font-size: 2em;
  }
  
  .auth-section, .call-section {
    padding: 20px;
  }
  
  .result-content {
    font-size: 0.8em;
  }
}
</style>